package com.googlecode.h0v3rk4rt.util;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class is used to test the one-way lag between
 * two computers over a network.
 * @author Nilay Kumar
 *
 */
public class LagTestClient {

	public static void main(String[] args) {
		try {
			System.out.print("Would you like to use TCP or UDP?");
			int option = System.in.read();
			if(option == 116) // TCP
				tcpTest();
			else // UDP
				udpTest();
		} catch (UnknownHostException e) {
			GameError.showErrorDialog(e);
		} catch (IOException e) {
			GameError.showErrorDialog(e);
		}
	}

	private static void tcpTest() throws UnknownHostException, IOException {
		System.out.println("Connecting to TCP server...");
		Socket connection = new Socket("127.0.0.1", 40313);
		ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
		oos.flush();
		System.out.println("Connected. Extracted streams. Writing data...");
		oos.writeObject(System.currentTimeMillis());
		System.out.println("Done.");
		connection.close();
	}
	
	private static void udpTest() throws IOException {
		System.out.println("Setting up UDP socket...");
		DatagramSocket socket = new DatagramSocket();
		byte[] buf = (System.currentTimeMillis() + "").getBytes();
		DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 40314);
		System.out.println("Sending DatagramPacket...");
		socket.send(packet);
		System.out.println("Done. Shutting down.");
		socket.close();
	}
}
